package cn.com.cnxfs.singlenetpassword;

import android.Manifest;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.telephony.SmsManager;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {
    private final String Authorization = "Basic c3hsZWU6eGZzMTIzNDU2WEZT"; //路由器管理账号密码
    private final String phoneNumber = "106593005"; //闪讯获取密码的短信平台号码
    private final String instruction = "mm"; //获取密码的短信
    private EditText username, password, server_addr;  //闪讯账号，动态密码，路由器地址
    private String message = "尊敬的闪讯用户，您的宽带上网密码是：123456,密码在2021-10-11 13:42:12以前有效";
    private final String[] permissions = {
            Manifest.permission.SEND_SMS, Manifest.permission.READ_SMS, Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.WRITE_CALENDAR, Manifest.permission.READ_CALENDAR
    };
    private final HandlerThread handlerThread = new HandlerThread("HandlerThread");

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final SharedPreferences preferences = getSharedPreferences("settings", MODE_PRIVATE);

        password = findViewById(R.id.password); //解析出来的密码
        username = findViewById(R.id.username);
        server_addr = findViewById(R.id.server_addr);
        username.setText(preferences.getString("username",""));
        server_addr.setText(preferences.getString("server",""));
        freshState(preferences, false); //上次的密码及有效期信息

        requestPermission(); //动态权限

        handlerThread.start();
        Handler handler = new Handler(handlerThread.getLooper(), msg -> {
            if (msg.what == 1) {
                message = msg.obj.toString();
                Log.d("最新接收的验证码是", message);
                final String passwd = message.substring(18, 24);
                final String ddl = message.substring(28, 47);
                preferences.edit().putString("password", passwd).putString("ddl", ddl).apply();
                runOnUiThread(() ->{
                    final EditText receiveMessage = findViewById(R.id.message); //收到的短信
                    final EditText deadline = findViewById(R.id.deadline); //解析出来的有效时间
                    receiveMessage.setText(message);
                    password.setText(passwd);
                    deadline.setText(ddl);
                    freshState(preferences, true);
                });
            }
            return true;
        });
        MyContent mycontent = new MyContent(this, handler);
        /*
        第一个参数是需要观察的uri，第二个参数true表示可以同时匹配这个uri的派生uri、false表示只可以
                精确匹配当前的uri.第三个参数是当检测到uri引起数据库变化时需要回调的观察类的实例对象*/
        getContentResolver().registerContentObserver(Uri.parse("content://sms"), true,mycontent);

        final Button button_send = findViewById(R.id.button_send); //发送短信的按钮
        button_send.setOnClickListener(view -> { //发送短信按钮
            SmsManager smsManager = SmsManager.getDefault();
            smsManager.sendTextMessage(phoneNumber, null, instruction, null, null);
            Toast.makeText(this, "短信发送成功！", Toast.LENGTH_SHORT).show();
        });

        final Button button_save = findViewById(R.id.button_save); //保存按钮
        button_save.setOnClickListener(view ->{
            preferences.edit()
                .putString("username", username.getText().toString())
                .putString("server", server_addr.getText().toString())
                .apply();
            Toast.makeText(this, "保存成功！", Toast.LENGTH_SHORT).show();
        });

        final Button button_check = findViewById(R.id.button_check); //检查按钮
        button_check.setOnClickListener(view ->{
            final String url = server_addr.getText().toString();
            if(url.equals("")){
                Toast.makeText(this, "请输入路由器地址！", Toast.LENGTH_SHORT).show();
                return;
            }
            new Thread(() -> {
                try {
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder().url(url+"/vpncli.asp#cfg")
                            .header("Authorization", Authorization).get().build();
                    Response response = client.newCall(request).execute();
                    final String res = response.body().string();
                    //Log.d("提交后的回复", res);
                    if(res.contains("vpnc_state_last = '1';"))
                        runOnUiThread(() -> Toast.makeText(MainActivity.this, "宽带连接成功！", Toast.LENGTH_SHORT).show());
                    else
                        runOnUiThread(() -> Toast.makeText(MainActivity.this, "宽带未连接！请更新密码！", Toast.LENGTH_SHORT).show());
                }catch (Exception e){
                    e.printStackTrace();
                    runOnUiThread(() -> Toast.makeText(MainActivity.this, "请求失败！请检查网络！", Toast.LENGTH_SHORT).show());
                }
            }).start();
        });

        final Button button_post = findViewById(R.id.button_post); //提交按钮
        button_post.setOnClickListener(view ->{
            final String _username = username.getText().toString();
            final String _password = password.getText().toString();
            if(_username.equals("")){
                Toast.makeText(this, "闪讯账号不能为空！", Toast.LENGTH_SHORT).show();
                return;
            }else if(_password.equals("")){
                Toast.makeText(this, "请先获取密码！", Toast.LENGTH_SHORT).show();
                return;
            }
            new Thread(() -> {
                try {
                    RequestBody x_www = new FormBody.Builder()
                            .add("current_page", "/vpncli.asp")
                            .add("next_page", "")
                            .add("next_host", "192.168.12.1")
                            .add("sid_list", "LANHostConfig;")
                            .add("group_id", "")
                            .add("action_mode", " Apply ")
                            .add("action_script", "")
                            .add("flag", "")
                            .add("vpnc_enable", "1")
                            .add("vpnc_fw_enable", "0")
                            .add("vpnc_fw_rules", "0")
                            .add("vpnc_type", "1")
                            .add("vpnc_peer", "61.164.18.22")
                            .add("vpnc_ov_port", "1194")
                            .add("vpnc_ov_prot", "0")
                            .add("vpnc_ov_mode", "1")
                            .add("vpnc_ov_auth", "0")
                            .add("vpnc_user", _username)
                            .add("vpnc_pass", _password)
                            .add("vpnc_auth", "0")
                            .add("vpnc_mppe", "0")
                            .add("vpnc_mtu", "1452")
                            .add("vpnc_mru", "1452")
                            .add("vpnc_pppd", "plugin hangzhou_sxplugin.so")
                            .add("vpnc_ov_mdig", "1")
                            .add("vpnc_ov_ciph", "3")
                            .add("vpnc_ov_clzo", "2")
                            .add("vpnc_ov_atls", "0")
                            .add("vpnc_ov_cnat", "0")
                            .add("vpnc_sfw", "0")
                            .add("vpnc_pdns", "0")
                            .add("vpnc_dgw", "1")
                            .add("scripts.vpnc_server_script.sh", "#!/bin/sh source /etc/storage/script/init.sh ### Custom user script ### Called after internal VPN client connected/disconnected to remote VPN server ### $1 - action (up/down) ### $IFNAME - tunnel interface name (e.g. ppp5 or tun0) ### $IPLOCAL - tunnel local IP address ### $IPREMOTE - tunnel remote IP address ### $DNS1 - peer DNS1 ### $DNS2 - peer DNS2 #copyright by hiboy # VPN国内外自动分流功能 0关闭；1启动 vpns=`nvram get vpnc_fw_enable` # VPN线路流向选择 0出国；1回国 vpnc_fw_rules=`nvram get vpnc_fw_rules` confdir=`grep conf-dir /etc/storage/dnsmasq/dnsmasq.conf | sed 's/.*\\=//g'` if [ -z \"$confdir\" ] ; then confdir=\"/tmp/ss/dnsmasq.d\" fi [ ! -d \"$confdir\" ] && mkdir -p $confdir restart_dhcpd # private LAN subnet behind a remote server (example) peer_lan=\"192.168.9.0\" peer_msk=\"255.255.255.0\" ### example: add static route to private LAN subnet behind a remote server func_ipup() { # route add -net $peer_lan netmask $peer_msk gw $IPREMOTE dev $IFNAME if [ \"$vpns\" = \"1\" ] ; then [ -f /tmp/vpnc.lock ] && logger -t \"【VPN 分流】\" \"等待45秒开始脚本\" I=45 while [ -f /tmp/vpnc.lock ]; do I=$(($I - 1)) [ $I -lt 0 ] && break sleep 1 done touch /tmp/vpnc.lock logger -t \"【VPN 分流】\" \"下载并运行 ip-pre-up 添加规则\" if [ ! -s \"/tmp/ip-pre-up\" ] ; then wgetcurl.sh /tmp/ip-pre-up \"$hiboyfile/ip-pre-up\" \"$hiboyfile2/ip-pre-up\" fi if [ ! -s \"/tmp/ip-pre-up\" ] ; then wgetcurl.sh /tmp/ip-pre-up \"$hiboyfile/ip-pre-up\" \"$hiboyfile2/ip-pre-up\" fi chmod 777 \"/tmp/ip-pre-up\" if [ \"$vpnc_fw_rules\" = \"1\" ] ; then /tmp/ip-pre-up $IPREMOTE else /tmp/ip-pre-up fi if [ ! -s \"/tmp/ip-down\" ] ; then wgetcurl.sh /tmp/ip-down \"$hiboyfile/ip-down\" \"$hiboyfile2/ip-down\" chmod 777 \"/tmp/ip-down\" fi if [ ! -s \"/tmp/ip-down\" ] ; then wgetcurl.sh /tmp/ip-down \"$hiboyfile/ip-down\" \"$hiboyfile2/ip-down\" fi rm -f /tmp/vpnc.lock logger -t \"【VPN 分流】\" \"ip-pre-up 添加规则完成\" else rm -f /tmp/vpnc.lock fi return 0 } func_ipdown() { # route del -net $peer_lan netmask $peer_msk gw $IPREMOTE dev $IFNAME if [ \"$vpns\" = \"1\" ] ; then [ -f /tmp/vpnc.lock ] && logger -t \"【VPN 分流】\" \"等待45秒开始脚本\" I=45 while [ -f /tmp/vpnc.lock ]; do I=$(($I - 1)) [ $I -lt 0 ] && break sleep 1 done touch /tmp/vpnc.lock logger -t \"【VPN 分流】\" \"下载并运行 ip-down 删除规则\" if [ ! -s \"/tmp/ip-down\" ] ; then wgetcurl.sh /tmp/ip-down \"$hiboyfile/ip-down\" \"$hiboyfile2/ip-down\" fi if [ ! -s \"/tmp/ip-down\" ] ; then wgetcurl.sh /tmp/ip-down \"$hiboyfile/ip-down\" \"$hiboyfile2/ip-down\" fi chmod 777 \"/tmp/ip-down\" /tmp/ip-down if [ -s \"/tmp/ip-pre-up\" ] ; then rm -f /tmp/ip-pre-up rm -f /tmp/ip-down fi rm -f /tmp/vpnc.lock logger -t \"【VPN 分流】\" \"ip-down 删除规则完成\" else rm -f /tmp/vpnc.lock fi return 0 } logger -t \"【VPN客户端脚本】\" \"$IFNAME $1\" case \"$1\" in up) func_ipup ;; down) func_ipdown ;; esac")
                            .add("vpnc_rnet", "")
                            .add("vpnc_rmsk", "")
                            .build();
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder().url(server_addr.getText().toString()+"/start_apply.htm")
                            .header("Authorization", Authorization).post(x_www).build();
                    Response response = client.newCall(request).execute();
                    final String res = response.body().string();
                    Log.d("提交后的回复", res);
                    runOnUiThread(() -> Toast.makeText(MainActivity.this, "提交成功！", Toast.LENGTH_SHORT).show());
                }catch (Exception e){
                    e.printStackTrace();
                    runOnUiThread(() -> Toast.makeText(MainActivity.this, "提交失败！请检查网络！", Toast.LENGTH_SHORT).show());
                }
            }).start();
        });
    }

    private void freshState(SharedPreferences preferences, boolean showNow){
        final String _lastTime = "上次密码："+preferences.getString("password", "")+"，有效期："+preferences.getString("ddl", "");
        final TextView lastTime = findViewById(R.id.lastTime);
        lastTime.setText(_lastTime);
        //显示上次的密码和有效期，下面开始判断密码是否已经过期
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINESE);
        simpleDateFormat.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
        Date date = null;
        try{
            date= simpleDateFormat.parse(preferences.getString("ddl", "2021-10-11 13:42:12"));
        }catch (Exception e){
            e.printStackTrace();
            date.setTime(System.currentTimeMillis());
        }
        Log.d("看看时间戳", date.getTime()+"");
        Log.d("当前时间戳", System.currentTimeMillis()+"");
        final TextView state = findViewById(R.id.state);
        if(date.getTime() > System.currentTimeMillis()){
            state.setText(R.string.valid); //未到期
            state.setTextColor(Color.GREEN);
        }else{
            state.setText(R.string.invalid); //已到期
            state.setTextColor(Color.RED);
        }
        if(showNow) { //添加日历提醒
            MyCalendar.deleteCalendarEvent(this, "更新闪讯密码"); //先删除旧的，再创建新的
            MyCalendar.insertCalendarEvent(this, "更新闪讯密码", "闪讯密码已到期，请及时获取新密码~",
                    date.getTime() + 60000, 0); //过期后再过1分钟才提醒
        }
    }

    private void requestPermission(){  //请求动态权限
        boolean flag = false;
        for(String s: permissions){
            if(PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(this, s)){
                flag = true;
                break;
            }
        }
        if(flag)
            ActivityCompat.requestPermissions(this, permissions, 1);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        for (int grantResult : grantResults) {
            if (grantResult != PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(this, "权限不足，无法使用！", Toast.LENGTH_LONG).show();
                finish();
            }
        }
    }

    @Override
    protected void onDestroy() {
        handlerThread.quitSafely();
        super.onDestroy();
    }
}